﻿using AnesSystem.Controls;
using AnesSystem.Models;
using AnesSystem.Services;
using AnesSystem.Util;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;

namespace AnesSystem.ViewModels
{
    public class AnesEventAndMedicineCtrlViewModel : MultitonBaseViewModel
    {
        #region Variables
        public List<EventAndDrug> _eventAndDrugList;

        public List<EventAndDrug> _drugList;

        public List<EventAndDrug> _eventList;

        public ObservableCollection<FrameworkElement> _eventAndDrugShowList;
       

        #endregion


        #region Constructor
        public AnesEventAndMedicineCtrlViewModel(int page)
        {
            CurPage = page;
            _eventAndDrugList = new List<EventAndDrug>();
            _drugList = new List<EventAndDrug>();
            _eventList = new List<EventAndDrug>();
            _eventAndDrugShowList = new ObservableCollection<FrameworkElement>();
        }

        #endregion


        #region Properties
        public List<EventAndDrug> EventAndDrugList
        {
            get
            {
                return _eventAndDrugList;
            }

            set
            {
                _eventAndDrugList = value;
            }
        }

        public List<EventAndDrug> DrugList
        {
            get
            {
                return _drugList;
            }

            set
            {
                _drugList = value;
            }
        }

        public List<EventAndDrug> EventList
        {
            get
            {
                return _eventList;
            }

            set
            {
                _eventList = value;
            }
        }

        public ObservableCollection<FrameworkElement> EventAndDrugShowList
        {
            get
            {
                return _eventAndDrugShowList;
            }

            set
            {
                _eventAndDrugShowList = value;
            }
        }

        public double FontSize
        {
            get
            {
                return PatientLink.AnesthesiaRecord.EventAndDrugFontSize;
            }

            set
            {
                PatientLink.AnesthesiaRecord.EventAndDrugFontSize = value;
            }
        }





        #endregion


        #region 依赖属性


        #endregion


        #region Event


        #endregion


        #region PrivateMethods


        #endregion


        #region Public/ProtectedMethods
        public override void InitData()
        {
            DateTime anesStartTime = DataManager.Instance.CurrentPatientLink.Status.AnesRecordStartTime;
            DateTime startTime = anesStartTime.AddHours((CurPage - 1) * 4);
            DateTime endTime = startTime.AddHours(4);
            if (!PatientLink.Status.OutRoomTime.Equals(new DateTime()) && endTime>=PatientLink.Status.OutRoomTime)
            {
                endTime = PatientLink.Status.OutRoomTime.AddSeconds(1);
            }
            AddSpecialDrug(EventAndDrugList);
            AddEvents(EventAndDrugList);
            string s = "";
            List<EventAndDrug> CurPageList = new List<EventAndDrug>();
            //事件与药物分开
            foreach (var item in EventAndDrugList)
            {
                if (item.IsDrug)
                {
                    DrugList.Add(item);
                }
                else
                {
                    EventList.Add(item);
                }
            }
            foreach (var item in EventList)
            {
                item.IsOperStatus = IsOperStatus(item.PatientEvents.Code);
            }
            try
            {
                //排序
                DrugList.Sort((EventAndDrug o1, EventAndDrug o2) =>
                {
                    s = o1.Name;
                    if (o1.Time == o2.Time)
                    {
                        if (o1.Name.Equals("入手术室"))
                        {
                            return -1;
                        }
                        if (o2.Name.Equals("出手术室"))
                        {
                            return -1;
                        }
                        //if (!o1.IsOperStatus)
                        //{
                        //    return -1;
                        //}
                        //if (o2.IsOperStatus)
                        //{
                        //    return -1;
                        //}

                        if (o1.IsOperStatus != o2.IsOperStatus)
                        {
                            if (!o1.IsOperStatus)
                            {
                                return -1;
                            }
                            else
                            {
                                return 1;
                            }
                        }
                            if (o1.InputTime < o2.InputTime)
                        {
                            return -1;
                        }
                        if (o1.InputTime > o2.InputTime)
                        {
                            return 1;
                        }
                        else
                        {
                            int ret = (o1.IsDrug ? o1.PatientDrugs.Id.ToString() : o1.PatientEvents.Id.ToString()).CompareTo(o2.IsDrug ? o2.PatientDrugs.Id.ToString() : o2.PatientEvents.Id.ToString());
                            if (ret > 0)
                            {
                                return 1;
                            }
                            else if (ret < 0)
                            {
                                return -1;
                            }
                            else
                            {
                                return 0;
                            }
                        }
                    }
                    else if (o1.Time < o2.Time)
                    {
                        return -1;
                    }
                    else if (o1.Time > o2.Time)
                    {
                        return 1;
                    }
                    else
                    {
                        return 0;
                    }
                });
               
            }
            catch (Exception ex)
            {
                Common.LogHelper.Error(s,this.GetType(), ex);
            }
            try
            {
                EventList.Sort((o1,o2) =>
                    {
                        s = o1.Name;
                        if (o1.Time == o2.Time)
                        {
                            if (o1.Name.Equals("入手术室"))
                            {
                                return -1;
                            }
                            if (o2.Name.Equals("出手术室"))
                            {
                                return -1;
                            }
                            if (o1.IsOperStatus != o2.IsOperStatus)
                            {
                                if (!o1.IsOperStatus)
                                {
                                    return -1;
                                }
                                else
                                {
                                    return 1;
                                }

                            }

                            if (o1.InputTime < o2.InputTime)
                            {
                                return -1;
                            }
                            if (o1.InputTime > o2.InputTime)
                            {
                                return 1;
                            }
                            else
                            {
                                int ret = (o1.IsDrug ? o1.PatientDrugs.Id.ToString() : o1.PatientEvents.Id.ToString()).CompareTo(o2.IsDrug ? o2.PatientDrugs.Id.ToString() : o2.PatientEvents.Id.ToString());
                                if (ret > 0)
                                {
                                    return 1;
                                }
                                else if (ret < 0)
                                {
                                    return -1;
                                }
                                else
                                {
                                    return 0;
                                }
                            }
                        }
                        else if (o1.Time < o2.Time)
                        {
                            return -1;
                        }
                        else if (o1.Time > o2.Time)
                        {
                            return 1;
                        }
                        else
                        {
                            return 0;
                        }
                    });
            }
            catch (Exception ex)
            {
                Common.LogHelper.Error(s, this.GetType(), ex);
            }
            CurPageList.Clear();
            for (int i = 0; i < DrugList.Count; i++)
            {
                DrugList[i].Index = i + 1;
                if (DrugList[i].Time >= startTime && DrugList[i].Time <endTime)
                {
                    CurPageList.Add(DrugList[i]);
                }
            }
            DrugList.Clear();
            DrugList.AddRange(CurPageList);
            CurPageList.Clear();
            for (int i = 0; i < EventList.Count; i++)
            {
                EventList[i].Index = i + 1;
                EventList[i].IsEdit = IsEdit(EventList[i].PatientEvents.Code);
                if (EventList[i].Time >= startTime && EventList[i].Time <endTime)
                {
                    CurPageList.Add(EventList[i]);
                }
            }
            EventList.Clear();
            EventList.AddRange(CurPageList);
        }

        /// <summary>
        /// 是否可以修改事件名称
        /// </summary>
        /// <returns></returns>
        public bool IsEdit(string code)
        {
            if (code.Equals(Constants.EVENT_ANES) || code.Equals(Constants.EVENT_IN_ROOM) || code.Equals(Constants.EVENT_OPERATION) || code.Equals(Constants.EVENT_SUB_REST)
                 || code.Equals(Constants.EVENT_IN_HUIFUSHI) || code.Equals(Constants.EVENT_CTRL_REST) || code.Equals(Constants.EVENT_QIGUAN_BAGUAN) || code.Equals(Constants.EVENT_QIGUAN_CHAGUAN))
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        public bool IsOperStatus(string code)
        {
            if (code.Equals(Constants.EVENT_ANES) || code.Equals(Constants.EVENT_OPERATION) || code.Equals(Constants.EVENT_QIGUAN_BAGUAN) || code.Equals(Constants.EVENT_QIGUAN_CHAGUAN))
            {
                return true;
            }
            else
            {
                return false;
            }
        }



        /// <summary>
        /// 取单次用药
        /// </summary>
        /// <param name="eventAndDrugList"></param>
        public void AddSpecialDrug(List<EventAndDrug> eventAndDrugList)
        {
            List<PatientDrugsModel> specialDrugList = OperationDataPool.Instance.CurOperationData.DrugsDataCache.AnesSpecialDrugList.ToList();
            if (specialDrugList != null && specialDrugList.Count > 0)
            {
                foreach (var item in specialDrugList)
                {
                    //string drugMethod = item.DrugMethod;
                    //string drugReason = item.DrugReason;
                    //string channel = item.Chanel;
                    //StringBuilder showName = new StringBuilder(item.Drugs.FullName);
                    //if (!string.IsNullOrEmpty(channel))
                    //{
                    //    showName.Append("(" + channel + ")");
                    //}
                    //if (!string.IsNullOrEmpty(drugMethod))
                    //{
                    //    showName.Append("(" + drugMethod + ")");
                    //}
                    //if (!string.IsNullOrEmpty(drugReason))
                    //{
                    //    showName.Append("(" + drugReason + ")");
                    //}
                    eventAndDrugList.Add(new EventAndDrug(item.InputTime, item.BeginTime, item.Drugs.FullName, item, true));
                }
            }
        }

        /// <summary>
        /// 取事件
        /// </summary>
        /// <param name="eventAndDrugList"></param>
        public void AddEvents(List<EventAndDrug> eventAndDrugList)
        {
            List<PatientEventsModel> events = OperationDataPool.Instance.CurOperationData.EventDataCache.SearchAllEventExe();
            if (events != null && events.Count > 0)
            {
                foreach (var item in events)
                {
                    ConfigEventsModel configEvent = DataManager.Instance.Code2events[item.Code];
                    if (configEvent.Single)
                    {
                        eventAndDrugList.Add(new EventAndDrug(item.InputTime, item.BeginTime, configEvent.Name, item, false, false));
                    }
                    else
                    {
                        if (item.EndTime.Equals(new DateTime()))
                        {
                            eventAndDrugList.Add(new EventAndDrug(item.InputTime, item.BeginTime, GetEventName(configEvent.Name, false), item, false, false));
                        }
                        else
                        {
                            eventAndDrugList.Add(new EventAndDrug(item.InputTime, item.BeginTime, GetEventName(configEvent.Name, false), item, false, false));
                            eventAndDrugList.Add(new EventAndDrug(item.InputTime, item.EndTime, GetEventName(configEvent.Name, true), item, false, true));
                        }
                    }
                }
            }
        }

        public string GetEventName(string eventName, bool isEnd)
        {
            if (eventName.Equals("入手术室"))
            {
                if (isEnd)
                {
                    return "出手术室";
                }
                else
                {
                    return eventName;
                }
            }
            if (eventName.Equals("入复苏室"))
            {
                if (isEnd)
                {
                    return "出复苏室";
                }
                else
                {
                    return eventName;
                }
            }
            if (isEnd)
            {
                return eventName + "结束";
            }
            else
            {
                return eventName + "开始";
            }
        }

        public override void Refresh()
        {
            Clear();
            InitData();
            CreatShowCtrl();
        }

        public virtual void Clear()
        {
            EventAndDrugList.Clear();
            DrugList.Clear();
            EventList.Clear();
            EventAndDrugShowList.Clear();
        }

        public virtual void CreatShowCtrl()
        {

            AddDrugTextBlock(0, true);
            for (int i = 0; i < DrugList.Count; i++)
            {
                AddDrugTextBlock(i, false);
            }

            AddEventTextBlock(0, true);
            for (int i = 0; i < EventList.Count; i++)
            {
                AddEventTextBlock(i, false);
            }
 //           CreatButton();
        }

        public void CreatButton()
        {
            WrapPanel wp = new WrapPanel();
            wp.Orientation = Orientation.Horizontal;

            Button addDrug = new Button();
            addDrug.Content = "药物";
            addDrug.SetBinding(Button.VisibilityProperty, new Binding("IsPrint")
            {
                Source = this,
                Mode = BindingMode.TwoWay
            });
            addDrug.Margin = new Thickness(0, 5, 40, 0);
            addDrug.Click += AddDrug_Click;

            addDrug.FontSize = 14;



            Button addEvent = new Button();
            addEvent.Content = "事件";
            addEvent.SetBinding(Button.VisibilityProperty, new Binding("IsPrint")
            {
                Source = this,
                Mode = BindingMode.TwoWay
            });
            addEvent.Margin = new Thickness(0, 5, 40, 0);
            addEvent.Click += AddEvent_Click;

            wp.Children.Add(addDrug);
            wp.Children.Add(addEvent);
            EventAndDrugShowList.Add(wp);


            addEvent.FontSize = 14;


        }

        public void AddDrug_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                SingleDrugConfigCtrlViewModel.Instance.PatientDrugsModel = new PatientDrugsModel();
                SingleDrugConfigCtrlViewModel.Instance.SetPatientDrug();
                DrugAndEventWindow.Instance.CusContent = SingleDrugConfigDialogCtrl.Instance;
                DrugAndEventWindow.Instance.Title = "编辑单次用药";
                DrugAndEventWindow.Instance.ShowDialog();
            }
            catch (Exception ex)
            {
                Common.LogHelper.Error(this.GetType(), ex);
            }
        }

        public void AddEvent_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                EventAndDrug ead = new EventAndDrug();
                EventAndDrugDialogCtrl.Instance.IsAutoShow = false;
                EventAndDrugDialogCtrl.Instance.EventAndDrug = ead;
                DrugAndEventWindow.Instance.CusContent = EventAndDrugDialogCtrl.Instance;
                DrugAndEventWindow.Instance.Title = "添加事件";
                DrugAndEventWindow.Instance.ShowDialog();
            }
            catch (Exception ex)
            {
                Common.LogHelper.Error(this.GetType(), ex);

            }
        }

        public virtual void AddDrugTextBlock(int index, bool flag)
        {
            if (flag)
            {
                AnesGeiYaoBtn btn = new AnesGeiYaoBtn();
                btn.Text = "<< 单次与其它药物 >>";
                btn.FontSize = 14;
                btn.Click += AddDrug_Click;
                EventAndDrugShowList.Add(btn);
            }
            else
            {
                EventAndDrugItemCtrl ctrl = new EventAndDrugItemCtrl();
                ctrl.CurFontSize = FontSize;
                ctrl.MouseLeftButtonDown += EventAndDrugCtrl_MouseDoubleClick;
                string str = "";
                StringBuilder builder = new StringBuilder();
                if (DrugList[index].Index < 10)
                {
                    str = "  " + DrugList[index].Index + "、" + DrugList[index].Time.ToString(DateFormat.DATE_FORMAT_STR_HM) + " ";
                    for (int i = 0; i < (str.Length - 1) * 2; i++)
                    {
                        builder.Append(" ");
                    }
                }
                else
                {
                    str = DrugList[index].Index + "、" + DrugList[index].Time.ToString(DateFormat.DATE_FORMAT_STR_HM) + " ";
                    for (int i = 0; i < str.Length * 2; i++)
                    {
                        builder.Append(" ");
                    }
                }


                ctrl.Margin = new Thickness(0, 5, 10, 0);
                ctrl.DisplayTime = str;
                ctrl.DisplayName = builder.ToString() + DrugList[index].Name;
                ctrl.DataContext = DrugList[index];
                EventAndDrugShowList.Add(ctrl);

            }
        }
        

        public void AddEventTextBlock(int index, bool flag)
        {
            if (flag)
            {
                AnesGeiYaoBtn btn = new AnesGeiYaoBtn();
                btn.Text = "<< 手术麻醉中事件 >>";
                btn.FontSize = 14;
                btn.Click += AddEvent_Click;
                EventAndDrugShowList.Add(btn);
            }
            else
            {
                EventAndDrugItemCtrl ctrl = new EventAndDrugItemCtrl();
                ctrl.CurFontSize = FontSize;
                ctrl.MouseLeftButtonDown += EventAndDrugCtrl_MouseDoubleClick;
                string str = "";
                StringBuilder builder = new StringBuilder();
                if (EventList[index].Index < 10)
                {
                    str = "  " + EventList[index].Index + "、" + EventList[index].Time.ToString(DateFormat.DATE_FORMAT_STR_HM) + " ";
                    for (int i = 0; i < (str.Length - 1) * 2; i++)
                    {
                        builder.Append(" ");
                    }
                }
                else
                {
                    str = EventList[index].Index + "、" + EventList[index].Time.ToString(DateFormat.DATE_FORMAT_STR_HM) + " ";
                    for (int i = 0; i < str.Length * 2; i++)
                    {
                        builder.Append(" ");
                    }
                }

                ctrl.DisplayTime = str;
                ctrl.Margin = new Thickness(0, 5, 10, 0);
                ctrl.DisplayName = builder.ToString() + EventList[index].Name;
                ctrl.DataContext = EventList[index];
                EventAndDrugShowList.Add(ctrl);
            }
        }
        public void AddAndMinFontsize(bool isAdd)
        {
            try
            {
                bool flag = false;
                if (isAdd)
                {
                    if (FontSize < 30)
                    {
                        FontSize += 1;
                        flag = true;
                    }
                }
                else
                {
                    if (FontSize > 10)
                    {
                        FontSize -= 1;
                        flag = true;
                    }
                }
                if (flag)
                {
                    PatientLinkService.Instance.AddUpdate(PatientLink);
                    Refresh();
                }
            }
            catch (Exception ex)
            {

                Common.LogHelper.Error(this.GetType(), ex);
            }
        }
        #endregion


        #region EventHandlers
        public void EventAndDrugCtrl_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            try
            {
                EventAndDrug eventAndDrug = (sender as EventAndDrugItemCtrl).DataContext as EventAndDrug;
                if (eventAndDrug.IsDrug)
                {
                    SingleDrugConfigCtrlViewModel.Instance.PatientDrugsModel = eventAndDrug.PatientDrugs;
                    SingleDrugConfigCtrlViewModel.Instance.SetPatientDrug();
                    DrugAndEventWindow.Instance.CusContent = SingleDrugConfigDialogCtrl.Instance;
                    DrugAndEventWindow.Instance.Title = "编辑单次用药";
                }
                else
                {
                    EventAndDrugDialogCtrl.Instance.IsAutoShow = true;
                    EventAndDrugDialogCtrl.Instance.EventAndDrug = (sender as EventAndDrugItemCtrl).DataContext as EventAndDrug;
                    DrugAndEventWindow.Instance.CusContent = EventAndDrugDialogCtrl.Instance;
                    DrugAndEventWindow.Instance.Title = "编辑事件";
                }

                DrugAndEventWindow.Instance.ShowDialog();
            }
            catch (Exception ex)
            {

                Common.LogHelper.Error(this.GetType(), ex);
            }
        }
        public void Ctrl_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {

            //List<ConfigEventsModel> list = DataManager.Instance.ConfigEventsModelList.ToList();
            //foreach (var item in list)
            //{
            //    item.Deleted = false;
            //    if (item.Code.Equals("event_1") || item.Code.Equals("event_2") || item.Code.Equals("event_3") ||  item.Code.Equals("event_4") || item.Code.Equals("event_6") )
            //    {
            //        item.Single = false;
            //    }
            //    else
            //    {
            //        item.Single = true;
            //    }
            //    ConfigEventModelService.Instance.AddUpdate(item);
            //}
        }

        #endregion

    }

    /// <summary>
    /// 单次药物与事件
    /// </summary>
    public class EventAndDrug : Common.ObservableObject
    {
        DateTime inputTime;
        DateTime time = DateTime.Now;
        string name = "";
        PatientDrugsModel patientDrugs;
        PatientEventsModel patientEvents;
        bool isDrug;
        bool isEnd;
        int index;
        bool isOperStatus = false;
        bool isEdit = true;

        public EventAndDrug()
        {
            patientEvents = new PatientEventsModel();
            patientDrugs = new PatientDrugsModel();
        }

        public EventAndDrug(DateTime inputTime, DateTime time, string name, PatientDrugsModel drugs, bool isDrug)
        {
            this.inputTime = inputTime;
            this.time = time;
            this.name = name;
            this.patientDrugs = drugs;
            this.isDrug = isDrug;

        }

        public EventAndDrug(DateTime inputTime, DateTime time, string name, PatientEventsModel eventExe, bool isDrug, bool isEnd)
        {
            this.inputTime = inputTime;
            this.time = time;
            this.name = name;
            this.patientEvents = eventExe;
            this.isEnd = isEnd;
            this.isDrug = isDrug;

        }

        public DateTime InputTime
        {
            get
            {
                return inputTime;
            }

            set
            {
                inputTime = value;
            }
        }

        public DateTime Time
        {
            get
            {
                if (time==null)
                {
                    time = DateTime.Now;
                }
                return time;
            }

            set
            {
                time = value;
                RaisePropertyChanged("Time");
            }
        }

        public string Name
        {
            get
            {
                return name;
            }

            set
            {
                name = value;
                RaisePropertyChanged("Name");
            }
        }

        public PatientDrugsModel PatientDrugs
        {
            get
            {
                return patientDrugs;
            }

            set
            {
                patientDrugs = value;
            }
        }

        public PatientEventsModel PatientEvents
        {
            get
            {
                return patientEvents;
            }

            set
            {
                patientEvents = value;
            }
        }

        public bool IsDrug
        {
            get
            {
                return isDrug;
            }

            set
            {
                isDrug = value;
            }
        }

        public bool IsEnd
        {
            get
            {
                return isEnd;
            }

            set
            {
                isEnd = value;
            }
        }

        public int Index
        {
            get
            {
                return index;
            }

            set
            {
                index = value;
            }
        }

        public bool IsEdit
        {
            get
            {
                return isEdit;
            }

            set
            {
                isEdit = value;
                RaisePropertyChanged("IsEdit");
            }
        }

        public bool IsOperStatus
        {
            get
            {
                return isOperStatus;
            }

            set
            {
                isOperStatus = value;
            }
        }
    }
}
